<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="search" label="关键字">
          <el-input
            v-model="queryParams.search"
            placeholder="站点编号、名称、描述"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增站点</el-button>
        </div>
      </div>
      <vxe-grid v-bind="gridOptions">
        <template #pager>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handlePageChange"
          />
        </template>
        <template #operate="scope">
          <el-button type="primary" link size="small" @click="handleOpenDialog(scope.row.id)">
            编辑
          </el-button>
          <el-button type="danger" link size="small" @click.stop="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button type="primary" link size="small" @click.stop="handleStatusChange(scope.row)">
            {{ scope.row.status == 1 ? "冻结" : "激活" }}
          </el-button>
        </template>
        <template #status="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
            {{ scope.row.status == 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
        <template #time="scope">
          {{ formatDate(scope.row[scope.column.field]) }}
        </template>
      </vxe-grid>

      <!-- 用户表单 -->
      <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        @close="handleCloseDialog"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="站点编号" prop="id">
            <el-input v-model="formData.id" placeholder="站点编号" :disabled="formData.is_update" />
          </el-form-item>
          <el-form-item label="站点名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入站点名称" />
          </el-form-item>
          <el-form-item label="站点描述" prop="title">
            <el-input v-model="formData.title" placeholder="请输入站点描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  name: "Station",
  inheritAttrs: false,
});
import DictDataAPI from "@/api/system/dict-data";
import { formatDate } from "@/utils/tools";
import StationAPI, { StationPageVO, StationPageQuery, StationForm } from "@/api/product/station";

const total = ref(0);
const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);
const dialog = reactive({
  visible: false,
  title: "新增站点",
});
const formData = reactive<Partial<StationForm>>({});

// Removed unitOptions since the related field is removed
const initFormData: Partial<StationForm> = {
  id: "",
  name: "",
  title: "",
  status: 0,
  is_update: false,
};

const rules = reactive({
  id: [
    {
      pattern: /(^[A-Za-z0-9_-]{4,15}$)/,
      message: "请输入站点编号",
      trigger: "blur",
    },
    { required: true, message: "编号不能为空", trigger: "blur" },
  ],
  name: [{ required: true, message: "站点名称不能为空", trigger: "blur" }],
});

const queryParams = reactive<StationPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const gridOptions = reactive<typeof VxeGridProps<StationPageVO>>({
  border: true,
  loading: false,
  id: "station",
  columns: [],
  data: [],
  columnConfig: {
    resizable: true,
  },
});

// 列配置
gridOptions.columns = [
  { field: "id", title: "站点编号", treeNode: true, width: 180 },
  { field: "name", title: "站点名称" },
  { field: "title", title: "站点描述" },
  { field: "status", title: "状态", width: 80, slots: { default: "status" } },
  { field: "create_time", title: "建立时间", width: 100, slots: { default: "time" } },
  { field: "update_time", title: "更新时间", width: 100, slots: { default: "time" } },
  { title: "操作", width: 180, slots: { default: "operate" }, fixed: "right" },
];

gridOptions.customConfig = {
  enabled: true,
  storage: {
    resizable: true,
  },
};

// 查询
function handleQuery() {
  gridOptions.loading = true;
  StationAPI.getPage(queryParams)
    .then((data) => {
      gridOptions.data = data.list;
      total.value = data.total;
    })
    .finally(() => {
      gridOptions.loading = false;
    });
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const station_id = formData.id as string;
      if (formData.is_update) {
        StationAPI.update(station_id, formData)
          .then(() => {
            ElMessage.success("修改站点成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      } else {
        StationAPI.add(formData)
          .then(() => {
            ElMessage.success("新增站点成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      }
    }
  });
}, 1000);

async function handleOpenDialog(id?: string) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改站点";
    formData.is_update = true;
    StationAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
    });
  } else {
    Object.assign(formData, initFormData);
    dialog.title = "新增站点";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.id = undefined;
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
}

const handlePageChange: typeof VxePagerEvents.PageChange = ({
  currentPage,
  pageSize,
}: {
  currentPage: number;
  pageSize: number;
}) => {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  handleQuery();
};

// 删除站点的操作
function handleDelete(row: StationPageVO) {
  ElMessageBox.confirm(`确认要删除该站点吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    StationAPI.delete(row.id).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  });
}

// 激活/冻结站点状态
function handleStatusChange(row: StationPageVO) {
  const text = row.status == 0 || row.status == 2 ? "启用" : "停用";
  ElMessageBox.confirm(`确认要${text}该站点吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let status = row.status == 0 || row.status == 2 ? 1 : 2;
    StationAPI.update(row.id, { status: status }).then(() => {
      row.status = status;
      ElMessage.success(`${text}成功`);
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
